﻿using System.Reflection;
using KinonekoSoftware.CodariaDB.Documents.Index;

namespace KinonekoSoftware.CodariaDB.Runtimes
{
    public class DatabaseBsonMapper : BsonMapper
    {
        public DatabaseBsonMapper() : base(null, new FallbackSupportTypeBinder())
        {
            
        }


        public static readonly DatabaseBsonMapper Override = new DatabaseBsonMapper();
    }
    
    public class FallbackSupportTypeBinder : ITypeNameBinder
    {
        private readonly Dictionary<string, Type> _fallbackMap = new Dictionary<string, Type>();

        public FallbackSupportTypeBinder()
        {
            SetFallback("KinonekoSoftware.CodariaDB.Documents.DataParts.Details.Part_ConnectionBasic, CodariaDB", typeof(Part_KizunaBasic));
            SetFallback("KinonekoSoftware.CodariaDB.Documents.DataParts.Details.Part_ConnectionDetail, CodariaDB", typeof(Part_KizunaDetail));
            SetFallback("KinonekoSoftware.CodariaDB.Documents.Index.TeamConnection, CodariaDB", typeof(TeamKizuna));
        }
        
        public static string GetNameImpl(Type type)
        {
            return type.FullName + ", " + type.GetTypeInfo().Assembly.GetName().Name;
        }

        public string GetName(Type type)
        {
            return type.FullName + ", " + type.GetTypeInfo().Assembly.GetName().Name;
        }

        public void SetFallback(string name, Type type)
        {
            if (string.IsNullOrEmpty(name) || type is null)
            {
                return;
            }
            
            //
            //
            _fallbackMap.TryAdd(name, type);
        }
        
        public Type GetType(string name)
        {
            if (_fallbackMap.Count == 0)
            {
                return Type.GetType(name);
            }

            if (!_fallbackMap.TryGetValue(name, out var type))
            {
                type = Type.GetType(name);
            }
            
            return type;
        }
    }
}